package com.aaa.sys.controller;


import com.aaa.vo.R;
import com.aaa.sys.entity.Position;
import com.aaa.sys.entity.User;
import com.aaa.sys.service.PositionService;
import com.aaa.sys.service.UserService;
import com.aaa.sys.util.ActivierUser;
import com.aaa.sys.vo.LoginVO;
import com.aaa.sys.vo.RoleSearch;
import com.aaa.sys.vo.UserPosition;
import com.aaa.sys.vo.UserSearch;
import com.aaa.util.JwtUtils;
import com.aaa.util.MD5Util;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 管理员表 前端控制器
 * </p>
 *
 * @author ykq
 * @since 2020-11-25
 */
@RestController
@RequestMapping("/system/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private PositionService positionService;
    /**
     * 退出
     */
    @PostMapping("/logout")
    public R logout(HttpServletRequest request){
         //得到请求头信息token
        String token = request.getHeader("token");
        //检验token是否有效
        if(!JwtUtils.checkToken(token)){
            return R.ok();
        }
        //解析该token得内容
        Long userid = JwtUtils.getMemberIdByJwtToken(token);
        //根据用户id清除redis
        stringRedisTemplate.delete("user::"+userid);
        return R.ok().data("userid",userid);
    }
        /**
         * 登陆方法
         * @param loginVO
         * @return
         */
      @PostMapping("login")
      public R login(@RequestBody LoginVO loginVO){
          ActivierUser activierUser = userService.queryUserByUserName(loginVO);
          if(activierUser==null){
               return R.error().message("账号或密码错误");
          }else{
              //1. 得到token.
              String token = JwtUtils.createJWT(activierUser.getUser().getUserId());
              //2 把当前登陆的用户信息以及角色和权限信息放入redis
              stringRedisTemplate.opsForValue().set("user::"+activierUser.getUser().getUserId(),JSON.toJSONString(activierUser),1, TimeUnit.DAYS);
              //3.把数据返回给前端
              return R.ok().message("登陆成功").data("token",token).data("activeUser",activierUser);
          }
      }

    /**
     * 根据条件分页查询所有用户
     */
    @PostMapping("selectByPageCon/{current}/{limit}")
    public R selectByPageCon(@PathVariable Integer current, @PathVariable Integer limit, @RequestBody UserSearch userSearch){
        IPage<UserPosition> page=this.userService.selectByPageCon(current,limit,userSearch);
        return R.ok().data("records",page.getRecords()).data("total",page.getTotal());
    }

    @PostMapping("updateStatus")
    public R updateStatus(@RequestParam("userId")Long userId,@RequestParam("status")String status){
        User user=new User();
        user.setStatus(status);
        user.setUserId(userId);
        this.userService.updateById(user);
        return R.ok().message("修改用户状态成功");

    }
    @PostMapping("deleteUser/{userId}")
    public R updateStatus(@PathVariable Long userId){
      try {
          this.userService.removeById(userId);
          return R.ok().message("删除用户成功");
      }catch (Exception e){
          return R.error().message("删除用户失败");
      }

    }

    @GetMapping("findById/{userId}")
    public R findById(@PathVariable Long userId){
        try {
           UserPosition userPosition= this.userService.getUserPosById(userId);
            List<Position> positions = this.positionService.list();
            return R.ok().data("userPos",userPosition).data("allPosition",positions);
        }catch (Exception e){
            return R.error().message("查询用户失败");
        }
    }

    @PostMapping("addUser")
    public R addUser(@RequestBody UserPosition userPosition){
        try {
            userPosition.setSalt((int)(Math.random()*10)+"acf");
            userPosition.setPassword(MD5Util.getSaltMD5(userPosition.getPassword(),userPosition.getSalt()));
            this.userService.saveUser(userPosition);
            return R.ok().message("添加用户成功");
        }catch (Exception e){
            e.printStackTrace();
            return R.error().message("添加用户失败");
        }
    }

    @PostMapping("updateUser")
    public R updateUser(@RequestBody UserPosition userPosition){
        try {
            this.userService.updateUser(userPosition);
            return R.ok().message("修改用户成功");
        }catch (Exception e){
            e.printStackTrace();
            return R.error().message("修改用户失败");
        }
    }

    @PostMapping("fenUserRole")
    public R fenUserRole(@RequestParam("userId")Long userId,@RequestParam("roleIds")List<Long> roleIds){
         this.userService.fenUserRole(userId,roleIds);
         return R.ok();
    }
    @PostMapping("selectUserById")
    public User selectUserById(@RequestParam Long id){
        return userService.getById(id);
    }
}













